package usf.vend.a.bull;

import java.util.ArrayList;

import usf.vend.a.bull.db.VendabullDBM;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SearchActivity extends Activity
{
	RadioGroup locationGroup;
	RadioButton gpsButton;
	RadioButton usfButton;
	RadioButton buildingButton;
	RadioButton collegeButton;
	
	RadioGroup productGroup;
	RadioButton foodButton;
	RadioButton beverageButton;
	
	private RadioButton checkedButton;
	private RadioButton checkedProdButton;
	
	Button searchButton;
	
	Spinner spinner;
	Spinner productSpinner;
	long selection;
	
	String currentLocation;
	
	Bundle bundle = new Bundle();
	private VendabullDBM DBManager;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        bundle = this.getIntent().getExtras();
        currentLocation = bundle.getString("location");
        DBManager = new VendabullDBM(this);
        
        locationGroup = (RadioGroup) findViewById(R.id.location_group);
        gpsButton = (RadioButton) findViewById(R.id.gps_button);
        usfButton = (RadioButton) findViewById(R.id.usf_button);
        buildingButton = (RadioButton) findViewById(R.id.building_button);
        collegeButton = (RadioButton) findViewById(R.id.college_button);
        spinner = (Spinner) findViewById(R.id.locationSpinner);
        spinner.setEnabled(false);
        
        productGroup = (RadioGroup) findViewById(R.id.product_group);
        foodButton = (RadioButton) findViewById(R.id.food_button);
        beverageButton = (RadioButton) findViewById(R.id.beverage_button);
        productSpinner = (Spinner) findViewById(R.id.productSpinner);
        productSpinner.setEnabled(false);
        
        searchButton = (Button) findViewById(R.id.search_button);
        
        setOnClickListeners();
    }
    
    @Override
    public void onStop()
    {
    	super.onStop();   	
    }
    
    private void setOnClickListeners()
    {
    	RadioButton.OnClickListener listener = new RadioButton.OnClickListener()
        {
        	public void onClick(View v)
        	{
        		int checkedId = locationGroup.getCheckedRadioButtonId();
        		checkedButton = (RadioButton) locationGroup.findViewById(checkedId);
        		if (checkedButton == usfButton)
        		{
        			spinner.setEnabled(false);
        		}
        		else if (checkedButton == gpsButton)
        		{
        			spinner.setEnabled(true);
        			fillSpinnerForGps();
        		}
        		else
        		{
        			spinner.setEnabled(true);
        			fillSpinner();
        		}
        	}
        };    	
        
        RadioButton.OnClickListener productListener = new RadioButton.OnClickListener()
        {
        	public void onClick(View v)
        	{
        		int checkedId = productGroup.getCheckedRadioButtonId();
        		checkedProdButton = (RadioButton) productGroup.findViewById(checkedId);
        		String text = checkedProdButton.getText().toString();
        		Toast.makeText(SearchActivity.this, text, Toast.LENGTH_SHORT).show();
        		if (!productSpinner.isEnabled())
        			productSpinner.setEnabled(true);
        		fillProductSpinner();
        	}
        };
        
        searchButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v)
        	{
        		onSearchButtonClick();
        	}
        });
        
       /*
        OnCheckedChangeListener checkedListener = new OnCheckedChangeListener()
        {
        	@Override
        	public void onCheckedChange(RadioGroup rg, int checkedId)
        	{
        		id = checkedId;
        	}
        }
        */
        
        gpsButton.setOnClickListener(listener);
        usfButton.setOnClickListener(listener);
        buildingButton.setOnClickListener(listener);
        collegeButton.setOnClickListener(listener);
        foodButton.setOnClickListener(productListener);
        beverageButton.setOnClickListener(productListener);
    }
    
    private void onSearchButtonClick()
    {		
		Cursor cur = getItemCursor();
		int latIndex = 1;
		int lngIndex = 1;
		String[] columns = cur.getColumnNames();
		String[] currentLoc = currentLocation.split(",");
		Location curLocation = new Location("");
		curLocation.setLatitude(Double.parseDouble(currentLoc[0]));
		curLocation.setLongitude(Double.parseDouble(currentLoc[1]));
		Location machLocation = new Location("");
		double distance;
		switch ((int) selection)
		{
		case 0:
			distance = 0.1 * 1609.344;
			break;
		case 1:
			distance = 0.2 * 1609.344;
			break;
		case 2:
			distance = 0.3 * 1609.344;
			break;
		case 3:
			distance = 0.4 * 1609.344;
			break;
		case 4:
			distance = 0.5 * 1609.344;
			break;
		default:
			distance = 1000;
		}
		for (int i = 0; i < cur.getColumnCount(); i++)
		{
			if (columns[i].equals("lat"))
				latIndex = i;
			else if (columns[i].equals("lng"))
				lngIndex = i;
		}
		
		Log.d("SearchActivity", "latIndex = " + latIndex);
		Log.d("SearchActivity", "lngIndex = " + lngIndex);
		ArrayList<String> coordinates = new ArrayList<String>();
		cur.moveToFirst();
		while (!cur.isAfterLast())
		{
			machLocation.setLatitude(Double.parseDouble(cur.getString(latIndex)));
			machLocation.setLongitude(Double.parseDouble(cur.getString(lngIndex)));
			if (checkedButton == gpsButton)
			{
				if (curLocation.distanceTo(machLocation) < distance)
				{
					coordinates.add(cur.getString(latIndex) + "," + cur.getString(lngIndex));
					Log.d("SearchActivity", "Added " +cur.getString(latIndex)+ "," +cur.getString(lngIndex));
				}
			}
			else
			{
				coordinates.add(cur.getString(latIndex) + "," + cur.getString(lngIndex));
				Log.d("SearchActivity", "Added " +cur.getString(latIndex)+ "," +cur.getString(lngIndex));
			}
			cur.moveToNext();
		}
		bundle.putStringArrayList("coordinates", coordinates);
		
		Intent intent = new Intent();
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		finish();
    }
    
    private void fillSpinner()
    {
    	Cursor cur;
    	DBManager.open();
    	String tableName = checkedButton.getText().toString().toLowerCase();
    	if (tableName.equals("building"))
    	{
    		tableName = VendabullDBM.BUILDINGS_TABLE;
    		cur = DBManager.getCursor(tableName);
    	}
    	else if (tableName.equals("college"))
    	{
    		tableName = VendabullDBM.COLLEGES_TABLE;
    		cur = DBManager.getCursor(tableName);
    	}
    	else
    	{
    		cur = DBManager.getCursor("machines");
    	}
    	
    	startManagingCursor(cur);
    	DBManager.close();
    	String from[];
    	from = new String[] {checkedButton.getText().toString().toLowerCase()};

    	
    	// create an array of the display item we want to bind our data to
    	int[] to = new int[]{R.id.search_list};
    	// create simple cursor adapter
    	SimpleCursorAdapter adapter =
    	  new SimpleCursorAdapter(this, R.layout.search_list_item, cur, from, to);
    	//adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item );
    	// get reference to our spinner
    	
    	spinner.setAdapter(adapter);
    	
    	spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    	    	selection = id;
    	    }
    	    public void onNothingSelected(AdapterView<?> parent) {
    	    }
    	});
    	//spinner.setOnItemSelectedListener(onSelectedListener);
    }
    
    private void fillProductSpinner()
    {
    	Cursor cur;
    	DBManager.open();
    	String tableName = checkedProdButton.getText().toString().toLowerCase();
    	if (tableName.equals("food"))
    	{
    		tableName = "foods";
    		cur = DBManager.getCursor(tableName);
    	}
    	else
    	{
    		tableName = "beverages";
    		cur = DBManager.getCursor(tableName);
    	}
    	
    	startManagingCursor(cur);
    	DBManager.close();
    	String from[];
    	//from = new String[] {checkedProdButton.getText().toString().toLowerCase()};
    	from = new String[] {"name"};

    	
    	// create an array of the display item we want to bind our data to
    	int[] to = new int[]{R.id.search_list};
    	// create simple cursor adapter
    	SimpleCursorAdapter adapter =
    	  new SimpleCursorAdapter(this, R.layout.search_list_item, cur, from, to);
    	//adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item );
    	// get reference to our spinner
    	
    	productSpinner.setAdapter(adapter);
    	
    	productSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    	    	selection = id;
    	    }
    	    public void onNothingSelected(AdapterView<?> parent) {
    	    }
    	});
    	//spinner.setOnItemSelectedListener(onSelectedListener);
    	//productSpinner.setEnabled(false);
    }
    
    private void fillSpinnerForGps()
    {
    	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
    			this, R.array.distances, android.R.layout.simple_spinner_item);
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spinner.setAdapter(adapter);
    	spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    	    	selection = id;
    	    }
    	    public void onNothingSelected(AdapterView<?> parent) {
    	    }
    	});
    }
    
    private Cursor getItemCursor()
    {
    	Cursor cur;
    	String name;
    	DBManager.open();
    	
    	if (productSpinner.isEnabled())
    		name = checkedProdButton.getText().toString().toLowerCase();
    	else if (spinner.isEnabled())
    		name = checkedButton.getText().toString().toLowerCase();
    	else
    		name = "usf";
    	
    	Log.d("SearchActivity", "checkedButton = " + name);
    	if (name.equals("usf") || name.equals("gps"))
    	{
    		Log.d("SearchActivity", "checkedButton = " + name);
    		cur = DBManager.getCursor(VendabullDBM.MACHINES_TABLE);
    	}
    	else if (name.equals("college"))
    	{
    		Log.d("SearchActivity", "name = college");
    		cur = DBManager.getMachinesByCollege(selection);
    	}
    	else if (name.equals("building"))
    	{
    		Log.d("SearchActivity", "name = building");
    		//cur = DBManager.getBuildings(selection);
    		cur = DBManager.getMachinesByBuilding(selection);
    	}
    	else if (name.equals("food"))
    	{
    		Log.d("SearchActivity", "name = food");
    		cur = DBManager.getMachinesByFood(selection);
    	}
    	else if (name.equals("beverage"))
    	{
    		Log.d("SearchActivity", "name = beverage");
    		cur = DBManager.getMachinesByBeverage(selection);
    	}
    	else
    	{
    		Log.d("SearchActivity", "name = else");
    		cur = DBManager.getMachines(selection);
    	}
    	DBManager.close();
    	Log.d("SearchActivity", "# of results = " + cur.getCount());
    	//Log.d("SearchActivity", "first _id = " + cur.getString(2));
    	Log.d("SearchActivity", "selection = " + selection);
    	return cur;
    }
}
